import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Form, Input, Select, DatePicker, Button, Space, message, Radio, Switch, InputNumber, Upload, Card, Row, Col, Tooltip } from 'antd';
import type { FormProps, UploadProps } from 'antd';
import { PlusOutlined, EditOutlined, LockOutlined, UserOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import http from '../api/http';
import { imgBaseURL,apiBaseURL } from '../api/baseURL';
import type { IUsers, IUsersWrite } from '../types/users';
import type { IRoles } from '../types/roles';
import type { IImage } from '~/types/system';


// 组件属性类型
interface UserFormModalProps {
  visible: boolean;
  title: string;
  initialValues?: Partial<IUsers>;
  userId?: number | null;
  loading: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

// 表单验证规则常量
const FORM_RULES = {
  loginName: [
    { required: true, message: '请输入登录账号' },
    { min: 2, message: '登录账号至少2个字符' }
  ],
  loginPwd: {
    add: [
      { required: true, message: '请设置登录密码' },
      { min: 3, message: '密码至少3个字符' }
    ],
    edit: [
      { min: 3, message: '密码至少个字符' }
    ]
  },
  userName: [
    { required: true, message: '请输入姓名' }
  ],
  sex: [
    { required: true, message: '请选择性别' }
  ],
  birthday: [
    { required: true, message: '请选择出生日期' }
  ],
  phone: [
    { required: true, message: '请输入手机号码' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  roleId: [
    { required: true, message: '请选择角色' }
  ]
};

const UserFormModal: React.FC<UserFormModalProps> = ({
  visible,
  title,
  initialValues,
  userId,
  loading,
  onCancel,
  onSuccess
}) => {
  const [form] = Form.useForm();
  //角色列表数据
  const [roles, setRoles] = useState<IRoles[]>([]);
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [uploading, setUploading] = useState<boolean>(false);
  const isEditMode = !!userId;

  const fetchRoles = useCallback(async (
  ) => {
    try {
      const response = await http.get<Array<IRoles>>('Roles');
      console.log('response: ', response);
      setRoles(response.data)
      
    } catch (error) {
      console.error('获取用户数据失败:', error);
      message.error('获取用户数据失败，请稍后重试');
    } finally {
    }
  }, []);

  // 表单初始化与重置
  useEffect(() => {
    //获取用户角色下拉数据
    fetchRoles();
  }, [])
  useEffect(() => {
    if (visible) {
      if (initialValues) {
        form.setFieldsValue({
          ...initialValues,
          birthday: initialValues.birthday ? dayjs(initialValues.birthday) : dayjs('2008-08-08'),
          lastTime: initialValues.lastTime ? dayjs(initialValues.lastTime) : dayjs(),
        });

        // 初始化头像
        if (initialValues.imgId && initialValues.path) {
          setAvatarUrl(`${imgBaseURL}${initialValues.path}`);
        } else {
          setAvatarUrl('');
        }
      } else {
        //自动重置 
        //form.resetFields();
        //手动重置
        form.setFieldsValue({
          sex: '男',
          status: true,
          imgId: 0,
          birthday: dayjs('2008-08-08'),
          loginName: '',
          loginPwd: '123456',
          userName: '',
          phone: '',
          roleId: 1
        });
        setAvatarUrl('');
      }
    }
  }, [visible, initialValues, form]);

  // 移除头像
  const handleRemoveAvatar = useCallback(() => {
    setAvatarUrl(''); 
    form.setFieldsValue({ imgId: 0 });
  }, [form]);

  // 头像上传处理
  const handleAvatarChange: UploadProps['onChange'] = (info) => {
    setUploading(info.file.status === 'uploading');
    if (info.file.status === 'done') {
      const response = info.file.response.data as IImage;
      console.log('头像上传response: ', response);

      if (response?.imgId && response.path) {
        form.setFieldsValue({ imgId: response.imgId });
        setAvatarUrl(imgBaseURL+response.path);
        message.success('头像上传成功');
      } else {
        message.error('头像上传失败，返回格式不正确');
      }
    } else if (info.file.status === 'error') {
      message.error('头像上传失败，请重试');
    }

    if (info.file.status === 'done' || info.file.status === 'error') {
      setUploading(false);
    }
  };

  // 表单提交处理
  const handleFormSubmit: FormProps<IUsersWrite>['onFinish'] = async (values) => {
    try {
      if (isEditMode && !userId) {
        message.error('用户ID不存在，无法修改');
        return;
      }

      const userData: IUsersWrite = {
        ...values,
        userId: isEditMode ? userId! : (values.userId ?? 0)
     
       
      };

      if (isEditMode) {

        console.log('Edit:userData: ', userData);
        const response = await http.put(`Users`, userData);
        console.log('response: ', response);

        if (response.code == '1') {
          message.success(response.msg);
          onSuccess();
          onCancel();
        }
        else {
          console.error('修改用户失败:', response.msg);
          message.error('修改用户失败，请稍后重试');
        }


      } else {
        if (!userData.loginPwd || userData.loginPwd.length < 3) {
          message.error('密码至少3个字符');
          return;
        }

        console.log('Add:userData: ', userData);
        const response = await http.post('Users', userData);
        console.log('response: ', response);

        if (response.code == '1') {
          message.success(response.msg);
          onSuccess();
          onCancel();
        }
        else {
          console.error('添加用户失败:', response.msg);
          message.error('添加用户失败，请稍后重试');
        }
      }

    } catch (error) {
      console.error(isEditMode ? '修改用户失败:' : '添加用户失败:', error);
      message.error(isEditMode ? '修改用户失败，请稍后重试' : '添加用户失败，请稍后重试');
    }
  };

  // 上传配置
  const uploadProps: UploadProps = {
    action: apiBaseURL + 'Upload', // 替换为实际上传接口
    headers: { authorization: 'Bearer token' },
    onChange: handleAvatarChange,
    showUploadList: false,
    listType: 'picture',
    disabled: uploading,
  };

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      footer={null}
      destroyOnHidden={true}
      maskClosable={false}
      width={700}
    >
      <div style={{
        padding: '0 40px',
        textAlign: 'center'
      }}>
        <Form<IUsersWrite>
          form={form}
          layout="vertical"
          onFinish={handleFormSubmit}
          initialValues={{
            sex: '男',
            status: true,
            imgID: 0,
            ...initialValues
          }}
        >
          {/* 头像上传区域 */}
          <Form.Item
            name="imgID"
            hidden // 隐藏ID输入，通过上传组件控制
          >
            <InputNumber />
          </Form.Item>

          {
            isEditMode&&
            <Form.Item
            name="loginPwd"
            hidden // 隐藏密码输入
          >
            <Input/>
          </Form.Item>
          }


          <Form.Item label="头像" style={{ marginBottom: 24 }} name="imgId">
            <Upload {...uploadProps}>
              <Card
                hoverable
                style={{
                  width: 160,
                  height: 160,
                  margin: '0 auto',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  border: '1px dashed #d9d9d9',
                  borderRadius: 8,
                  position: 'relative'
                }}
              >
                {avatarUrl ? (
                  <>
                    <img
                      src={avatarUrl}
                      alt="用户头像"
                      style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                        borderRadius: 6
                      }}
                    />
                    <div style={{
                      position: 'absolute',
                      bottom: 0,
                      left: 0,
                      right: 0,
                      backgroundColor: 'rgba(0,0,0,0.5)',
                      color: 'white',
                      padding: '4px 0',
                      fontSize: 12,
                      borderRadius: '0 0 6px 6px',
                      display: 'flex',
                      justifyContent: 'space-around'
                    }}>
                      <span>点击更换</span>
                      <Tooltip title="移除头像">
                        <DeleteOutlined
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRemoveAvatar();
                          }}
                          style={{ cursor: 'pointer' }}
                        />
                      </Tooltip>
                    </div>
                  </>
                ) : (
                  <div style={{ textAlign: 'center', color: '#666' }}>
                    <UploadOutlined style={{ fontSize: 28, marginBottom: 8 }} />
                    <div>点击上传头像</div>
                    <div style={{ fontSize: 12, marginTop: 4, color: '#999' }}>
                      支持JPG、PNG格式
                    </div>
                  </div>
                )}
                {uploading && (
                  <div style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(255,255,255,0.7)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                  }}>
                    <span>上传中...</span>
                  </div>
                )}
              </Card>
            </Upload>
          </Form.Item>

          {/* 使用栅格系统实现不同长度控件 */}
          <Row gutter={[24, 16]}>
            <Col span={12}>
              <Form.Item
                name="loginName"
                label="登录账号"
                rules={FORM_RULES.loginName}
              >
                <Input
                  placeholder="请输入登录账号"
                  prefix={<UserOutlined />}
                  disabled={isEditMode}
                />
              </Form.Item>
            </Col>

            <Col span={12}>
              {!isEditMode &&
                <Form.Item
                  name="loginPwd"
                  label="登录密码"
                  rules={isEditMode ? FORM_RULES.loginPwd.edit : FORM_RULES.loginPwd.add}
                >
                  <Input.Password
                    placeholder={isEditMode ? "不修改密码请留空" : "请设置登录密码"}
                    prefix={<LockOutlined />}
                  />
                  {isEditMode && (
                    <p style={{ marginTop: 5, fontSize: 12, color: '#666' }}>
                      不修改密码请留空
                    </p>
                  )}
                </Form.Item>
              }
            </Col>
          </Row>

          <Row gutter={[24, 16]}>
            <Col span={12}>
              <Form.Item
                name="roleId"
                label="角色"
                rules={FORM_RULES.roleId}
              >
                <Select placeholder="请选择角色" style={{ width: '100%' }}>
                  {roles.map(role => (
                    <Select.Option key={role.roleId} value={role.roleId}>
                      {role.roleName}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="userName"
                label="姓名"
                rules={FORM_RULES.userName}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>


          </Row>

          <Row gutter={[24, 16]}>
            <Col span={12}>
              <Form.Item
                name="birthday"
                label="出生日期"
                rules={FORM_RULES.birthday}
              >
                <DatePicker
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                  style={{ width: '100%' }}
                  disabledDate={(current) => current && current > dayjs().endOf('day')}
                />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号码"
                rules={FORM_RULES.phone}
              >
                <Input placeholder="请输入手机号码" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[24, 16]} style={{ textAlign: 'left' }}>
            <Col span={12}>
              <Form.Item
                name="sex"
                label="性别"
                rules={FORM_RULES.sex}
              >
                <Radio.Group style={{ width: '100%' }} optionType="button" buttonStyle="solid">
                  <Radio.Button value="男">男</Radio.Button>
                  <Radio.Button value="女">女</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Col>


            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ textAlign: 'center', marginTop: 32 }}>
            <Space size="middle">
              <Button onClick={onCancel} style={{ width: 120 }}>取消</Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading || uploading}
                icon={isEditMode ? <EditOutlined /> : <PlusOutlined />}
                style={{ width: 140 }}
              >
                {isEditMode ? '立即修改' : '立即添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default UserFormModal;
